import React from "react";
import {Card} from "antd";
import {connect} from "dva";
import {FormattedMessage} from "@@/plugin-locale/localeExports";
import {CardProps, CardTabListType} from "antd/lib/card";
import {GlobalModelState} from "@/models/global";
import {FunctionVO} from "@/types/function";
import styles from './index.less';
import classNames from "classnames";

interface TabCardPermissionProps extends Omit<CardProps,"tabList" | "tabBarExtraContent">{
  functions:FunctionVO[],
  functionObject:{
    [key:string]: {
      extra?:React.FC,
      component:React.FC,
    }
  },
}

interface TabCardPermissionState{
  activeTabKey?: string,
  tabList: CardTabListType[]
}

const transformState=(props:TabCardPermissionProps):TabCardPermissionState=>{
  const {functionObject,functions}=props;
  const functionKeys=Object.keys(functionObject);
  const tabList=functionKeys
    // ?.filter(functionKey=>{
    //   return functions?.some(item=>functionKey===item.path);
    // })
    ?.map(functionKey=>{
      return {
        key:functionKey, tab:<FormattedMessage id={functionKey} />
      }
    });
  return {
    tabList:tabList,
    activeTabKey:tabList.length>0?tabList[0].key:undefined,
  }
}

class TabCardPermission extends React.Component<TabCardPermissionProps, TabCardPermissionState> {

  state={
    tabList:[],
    activeTabKey:'',
  };

  componentDidMount() {
    this.setState(transformState(this.props))
  }

  onTabChange=(activeTabKey:string)=>{
    this.setState({activeTabKey});
  }

  render() {

    const { functionObject,functions } = this.props;
    const { activeTabKey,tabList } = this.state;

    const props:any={...this.props};
    delete props.functions;
    delete props.functionObject;
    delete props.dispatch;

    if(functions&&tabList.length>0){
      // @ts-ignore
      const TabComponent=functionObject[activeTabKey].component;
      const TabBarExtra=functionObject[activeTabKey].extra;
      return (
        <Card
          {...props}
          className={classNames(styles['tab-card'],this.props.className)}
          tabList={tabList}
          activeTabKey={activeTabKey}
          onTabChange={this.onTabChange}
          tabBarExtraContent={TabBarExtra&&<TabBarExtra />}
        >
          {TabComponent&&<TabComponent />}
        </Card>
      );
    }
    return null;
  }
}

export default connect(({global}:{
  global: GlobalModelState;
}) => ({
  functions:global.profile.functions
}))(TabCardPermission);
